var startX = 0,startY = 0;
var canvasLayer, canvasContainer;
var activeBaby;
$(function() {
	
	$('ul.navbar li a').click(function(e) {
		$('ul.navbar li a').removeClass('active');
		var $this = $(this);
		if (!$this.hasClass('active')) {
		$this.addClass('active');
		}
		e.preventDefault();
	});
	
	$("#picture-upload").click(function(e){
		$("#upload-dialog").modal('show');
		e.preventDefault();
	});
	
	$("#background-picker").ColorPicker({
			onSubmit: function (hsb, hex, rgb, el) {
				changeBg(hex);
				$(el).ColorPickerHide();
			}
	});
	

	$('#picture-trigger').click(function(e) {
		$('#pictureList').modal('show');
		$.getJSON('getpictures.php', function(data) {
		  $("#images").empty();
  		  $.each(data, function(key, val) {
  			  $.each(val, function(innerKey, innerValue) {
  				$("<img/>").attr("src", "img.php?q="+innerValue.url)
  					.appendTo("#images")
  					.attr("id", innerValue.id)
  					.css("max-width", "200px")
		        	.css("max-height", "300px")
  					.on('click',function(event){
  						draw($(this));
  					});
  			  });
  		  });
		});
	    e.preventDefault();
	});
	
	$('#picture-save').click(function(e) {
		//var canvas = getElementByid("idcan");
		//var picture = $("div#container > div > canvas")[0].toDataURL("images/png");
		var picture = $("canvas")[0].toDataURL("images/png");
		$.post('scrap_save.php',{image:picture},
			function(file){
				$("#save-scrap-dialog").modal('show');
//				$("#save-scrap-dialog").lightbox_me({
//					centered:true,
//					onLoad: function() {}
//				});
				
				if($("#addScrapTitleDescription img").length == 0){
//					var jsonResult = $.parseJSON(file);
//					alert(file);
	    			$("#addScrapTitleDescription").attr({action:file.picPath,method:"POST"});
	    			$("#addScrapTitleDescription").append("<p style='border:1px dashed #ccc;'><img src='img.php?q="+file.picPath+"' style='max-width:300px;max-height:300px;'/></p>");
	    			$("#addScrapTitleDescription").append("<p><label for='title'>Title</label><input type='text' name='title' id='title'/></p>");
	    			$("#addScrapTitleDescription").append("<p><label for='description'>description</label><input type='text' name='description' id='description'/></p>");
        			$("#addScrapTitleDescription").append("<p><label for='tag'>tag</label><input type='text' name='tag' id='tag'/></p>");
	    			$("#addScrapTitleDescription").append("<p><button id='sendPictureDetail' onclick='sendScrapTitleDescription()'>save title and description</button></p>");
	    			$("#addScrapTitleDescription").show();
	    		}
	    	}
		);
	});
	
	$('#resize-trigger').click(function(e) {
		$('#resize-dialog').lightbox_me({
			centered:true,
			onClose: function() {
				resize($("#newWidth").val(), $("#newHeight").val());
			}
	    });
		e.preventDefault();
		$("#newWidth").val(activeBaby.getWidth());
		$("#newHeight").val(activeBaby.getHeight());
	});
	
	$('#pictureUploader').fileupload({
        dataType: 'multipart/form-data',
        add: function (e, data) {
        	var jqXHR = data.submit()
        		.complete(function (result, textStatus, jqXHR) {
            		if($("#addTitleDescription img").length == 0){
            			var jsonResult = $.parseJSON(result.responseText);
            			$("#addTitleDescription").attr({action:jsonResult.url,method:"POST"});
            			$("#addTitleDescription").append("<p><img src='img.php?q="+jsonResult.url+"' style='max-width:300px;max-height:300px;'/></p>");
            			$("#addTitleDescription").append("<p><label for='title'>Title</label><input type='text' name='title' id='title'/></p>");
            			$("#addTitleDescription").append("<p><label for='description'>description</label><input type='text' name='description' id='description'/></p>");
            			$("#addTitleDescription").append("<p><label for='tag'>tag</label><input type='text' name='tag' id='tag'/></p>");
            			$("#addTitleDescription").append("<p><button id='sendPictureDetail' class='btn' onclick='sendTitleDescription()'>save title and description</button></p>");
            			$("#addTitleDescription").show();
            		}
            	});
        }
    });
	
	$('#search').keypress(function(event){
		var keycode = (event.keyCode ? event.keyCode : event.which);
		var id = document.getElementById("searching").value;
		if(keycode == '13'){
			$.getJSON('services/manager/friendProfile/'+id, function(detail) {
				if (detail.emailAddress === null) {
					alert("User tidak ditemukan.");
				} else {
					alert(detail.emailAddress);
				}
			});
		}
	});
	
	$("#upload-dialog").css("display", "none");
	$("#resize-dialog").css("display", "none");
	$("#pictureList").css("display", "none");
	$("#addTitleDescription").hide();
	$("#addScrapTitleDescription").hide();
	$("#save-scrap-dialog").hide();
	
});
window.onload = function() {
	var stage = new Kinetic.Stage({
		container : "container",
		width : 600,
		height : 450
	});

	var layer = new Kinetic.Layer();
	canvasLayer = layer;
	stage.add(layer);
	//backgroundLayer = new Kinetic.Layer();
	stage.setOpacity(1);
	//stage.add(backgroundLayer);
	canvasContainer = stage;
};

function sendTitleDescription() {
	$.ajax({
		//url: $("#addTitleDescription").attr("action"),
		url: "saveupload.php?id="+$("#addTitleDescription").attr("action"),
		dataType: "json",
		type: "POST",
		data: {title: $("#addTitleDescription #title").val(), description:$("#addTitleDescription #description").val()},
		//data:$("#addTitleDescription").serialize();
		success: function(data){
			 $('#upload-dialog').modal('toggle');
		},
		error: function () {
	         $('#upload-dialog').modal('hide'); // request fails, hide the modal.
	    },
	    timeout: function () {
	         $('#upload-dialog').modal('hide'); // request times out, hide the modal.
	    }
	});
}

function sendScrapTitleDescription() {
   //alert($("#addScrapTitleDescription").attr("action"));
	$.ajax({
		url: "savescraptitle.php?q="+$("#addScrapTitleDescription").attr("action"),
		dataType: "json",
		type: "POST",
		data: {title: $("#addScrapTitleDescription #title").val(), description:$("#addScrapTitleDescription #description").val(), tag:$("#addScrapTitleDescription #tag").val()},
		success: function(data){
			$('#save-scrap-dialog').modal('hide');
		}
	});
}

function draw(image){
    var img = image.get(0);
    var baby = new Kinetic.Image({
		x : startX,
		y : startY,
		image : img,
		width : img.width,
		height : img.height,
		draggable:true,
		name: 'baby'
	});
    
    baby.on("click", function(){
    	if(baby.getStrokeWidth() > 0) {
    		activeBaby = null;
    		baby.setStroke('');
        	baby.setStrokeWidth(0);
        	baby.stroke();
    	} else {
    		activeBaby = baby;
    		baby.setStroke('black');
    		baby.setStrokeWidth(5);
    		baby.stroke();
    	}
    });
    activeBaby = baby;
    canvasLayer.add(baby);
    canvasLayer.draw();
    
}

function changeBg(color){
	$("#container canvas").css("background-color","#"+color);
}

function resize(newWidth, newHeight) {
	activeBaby.setWidth(newWidth);
	activeBaby.setHeight(newHeight);
	canvasLayer.draw();
}

function crop(sx, sy, sw, sh, dx, dy, dw, dh) {
	
}
